package com.shao.im.controller;


import com.shao.commons.domain.R;
import com.shao.im.entity.Post;
import com.shao.im.entity.PostImg;
import com.shao.im.entity.vo.PostListVo;
import com.shao.im.entity.vo.SharePostVo;
import com.shao.im.service.CommentService;
import com.shao.im.service.PostImgService;
import com.shao.im.service.PostService;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;

/**
 * 动态表(Post)表控制层
 *
 * @author makejava
 * @since 2023-08-04 22:23:23
 */
@RestController
@RequestMapping("/post")
@Slf4j
public class PostController {
    /**
     * 服务对象
     */
    @Resource
    private PostService postService;
    @Resource
    private PostImgService postImgService;
    @Resource
    private CommentService commentService;

    /**
     * 查询当前登录用户的动态以及当前用户的好友的动态
     * 查询当前用户的好友的动态 - select * from post where uid in (select fid from friends_relations where uid = ?);
     * @return 返回
     */
    @RequestMapping("/queryPost")
    public R<List<PostListVo>> queryMyPost(@RequestParam("uid") Integer uid) {
        // System.out.println("uid--->" + uid);
        List<PostListVo> postList = postService.queryPostListByMeAndFids(uid);
        for (PostListVo postListVo : postList) {
            postListVo.setImages(postImgService.queryImages(postListVo.getPid()))
                    .setComments(commentService.queryCommentByPid(postListVo.getPid()));
        }
        log.debug("[postList] 当前用户及好友列表的动态 - {}", postList);
        return R.success(postList);
    }

    /**
     * 发动态
     * @param sharePostVo
     * @return
     */
    @RequestMapping("/sharePost")
    @Transactional
    public R sharePost(SharePostVo sharePostVo) {
        // 保存动态
        Post post = new Post()
                .setUid(sharePostVo.getUid())
                .setContent(sharePostVo.getContent());
        postService.save(post);
        //log.debug("[post] 主键回填之后的post - {}", post);
        // 保存朋友圈图片
        for (String imgName : sharePostVo.getImageList()) {
            postImgService.save(new PostImg()
                    .setPid(post.getPid())
                    .setImg(imgName));
        }
        return R.success();
    }
}

